/*
 * @Descripttion: 
 * @version: 
 * @Author: Miller Zhou
 * @Date: 2021-02-18 13:51:27
 * @LastEditors: Miller Zhou
 * @LastEditTime: 2021-02-20 15:34:31
 */
#include "Ziic.h"


#ifdef mcu_stm32f1_hal


#ifdef Software_IIC
/*
	Config the output mode of SCL, SDA
*/
void SCL_L(void)
{
	HAL_GPIO_WritePin(SCL, GPIO_PIN_RESET);
}
void SCL_H(void)
{
	HAL_GPIO_WritePin(SCL, GPIO_PIN_SET);
}
void SDA_L(void)
{
	HAL_GPIO_WritePin(SDA, GPIO_PIN_RESET);
}
void SDA_H(void)
{
	HAL_GPIO_WritePin(SDA, GPIO_PIN_SET);
}

/*
	Config the fundamental function of IIC protocol
*/
/*To Generate IIC start signal*/
void IIC_Start(void)
{
	SDA_OUT();
	SDA_H();
	SCL_H();
	Z_delay_us(5);
	SDA_L();
	Z_delay_us(5);
	SCL_L();
}

/*To Generate IIC end signal*/
void IIC_Stop(void)
{
	SDA_OUT();
	SCL_L();
	SDA_L();
	Z_delay_us(4);
	SCL_H();
	Z_delay_us(4);
	SDA_H();
}

/*
	IIC protocol sends a byte, and returns whether the slave responds
	- 1, yes
	- 0, no
*/
void IIC_Send_Byte(uint8_t txd)
{
	uint8_t t;
	SDA_OUT();
	SCL_L();

	for (t = 0; t < 8; t++)
	{
		if (txd&0x80)
			SDA_H();
		else
			SDA_L();
		txd <<= 1;
		Z_delay_us(2);
		SCL_H();
		Z_delay_us(2);
		SCL_L();
		Z_delay_us(2);
	}
}

/*Read a byte from the other equipment*/
uint8_t IIC_Read_Byte(unsigned char ack)
{
	unsigned char i, received=0;
	SDA_IN();
	for (i = 0; i < 8; i++)
	{
		SCL_L();
		Z_delay_us(2);
		SCL_H();
		received<<=1;
		if (HAL_GPIO_ReadPin(SDA)) received++;
		Z_delay_us(1);
	}
	if (!ack) IIC_NAck();
	else IIC_Ack();
	return received;
}

/*
	Waiting for the respond signal
	return: - 1, Failed to recived 
			- 0, Success to Recived
*/
uint8_t IIC_Wait_Ack(void)
{
	uint8_t ErrTime = 0;
	SDA_IN();
	SDA_H();
	Z_delay_us(1);
	SCL_H();
	Z_delay_us(1);

	while (HAL_GPIO_ReadPin(SDA))
	{
		ErrTime++;
		if (ErrTime > 250)
		{
			IIC_Stop();
			return 1;
		}
	}
	SCL_L();
	return 0;
}

/*To Generate the respond signal*/
void IIC_Ack(void)
{
	SCL_L();
	SDA_OUT();
	SDA_L();
	Z_delay_us(2);
	SCL_H();
	Z_delay_us(2);
	SCL_L();
}

/*Don't generate the respond signal*/
void IIC_NAck(void)
{
	SCL_L();
	SDA_OUT();
	SDA_H();
	Z_delay_us(2);
	SCL_H();
	Z_delay_us(2);
	SCL_L();
}
#endif
#ifdef Hardware_IIC

extern I2C_HandleTypeDef  hi2c1;
void i2c_write_byte(uint16_t dev_add, uint16_t mem_add, uint8_t data)
{
    HAL_I2C_Mem_Write(&hi2c1 ,dev_add<<1, mem_add, 1, (uint8_t *)&data, 1, 0xfff);
}
void i2c_write_len(uint16_t dev_add, uint16_t mem_add, uint16_t mem_size, uint8_t *data, uint16_t buff_size)
{
    HAL_I2C_Mem_Write(&hi2c1 ,dev_add<<1, mem_add, mem_size, data, buff_size, 0xfff);
}
#endif

#endif


